import type { FormRules } from "element-plus";
import { reactive } from "vue";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";

/** 自定义表单规则校验 */
// 添加一个变量来存储原始设备ID
let originalDeviceId = 0;

// 导出一个函数来设置原始设备ID
export function setOriginalDeviceId(id: number, _tenantId: number) {
  originalDeviceId = id;
}

export function getFormRules(id: number, tenantId: number) {
  // 设置原始设备ID
  setOriginalDeviceId(id, tenantId);

  return reactive(<FormRules>{
    name: [{ required: true, message: "设备名称为必填项", trigger: "blur" }],
    code: [
      { required: true, message: "设备编码为必填项", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (!value) {
            callback();
            return;
          }
          // 如果原始设备ID存在且与当前值相同，则不进行唯一性验证
          if (originalDeviceId) {
            callback();
            return;
          }

          // 使用IIFE包装异步代码
          (async () => {
            try {
              // 发送请求检查设备编码是否存在
              const res = await http.get(
                changeHttpLink("/api/Device/check-code-unique"),
                {
                  params: {
                    code: value,
                    tenantId: tenantId,
                    excludeId: originalDeviceId ? originalDeviceId : undefined
                  }
                }
              );
              // 添加类型断言以解决TypeScript类型检查问题
              const typedRes = res as {
                Success: boolean;
                Data?: boolean;
              };
              if (typedRes.Success && !typedRes.Data) {
                callback(new Error("设备编码已存在"));
              } else {
                callback();
              }
            } catch (error) {
              console.error(error);
              callback(new Error("验证设备编码失败，请重试"));
            }
          })();
        },
        trigger: "blur"
      }
    ],
    type: [{ required: true, message: "请选择设备类型", trigger: "change" }],
    groupId: [{ required: true, message: "请选择设备组", trigger: "change" }]
  });
}
